package de.earthquake.downloadfile;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import de.earthquake.CONSTANTS;
import de.earthquake.FragmentActivity;
import de.earthquake.R;

public class DownloadEarthquakeFile extends AsyncTask<Void, Void, Void>{

	private static final String TAG = DownloadEarthquakeFile.class.getCanonicalName();
	private Context context;
	private ProgressDialog dialog;
	public DownloadEarthquakeFile(Context context) {
		this.context = context;
		dialog = new ProgressDialog(context);
		dialog.setTitle(context.getString(R.string.please_wait));
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog.show();
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		try {
			URL url = new URL(CONSTANTS.URL);
			URLConnection connection = url.openConnection();
			connection.connect();
			
			InputStream input = new BufferedInputStream(url.openStream());
			OutputStream output = new FileOutputStream(CONSTANTS.PATH_TO_XML_FILE);
			
			byte data[] = new byte[1024];
            int count;
            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }
			
			output.flush();
			output.close();
			input.close();
			
		} catch (Exception e) {
			Log.e(TAG, e.getLocalizedMessage(), e);
		}
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		context.startActivity(new Intent(context, FragmentActivity.class));
	}

}
